import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    redirect: '/home',
    component: () => import('@/views/layout/LayoutView.vue'),
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/IndexHome.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/user/UserView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/student',
        name: 'student',
        component: () => import('@/views/user/StudentView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/teacher',
        name: 'teacher',
        component: () => import('@/views/user/TeacherView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/course',
        name: 'course',
        component: () => import('@/views/class/CourseView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/grade',
        name: 'grade',
        component: () => import('@/views/class/GradeView.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/LoginView.vue')
  }
]

const router = new VueRouter({
  routes
})
// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 判断该路由是否需要认证
    if (!store.state.token) {
      // 如果没有token，重定向到登录页面，并显示提示框
      Message.error('请登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将要跳转的路由路径作为参数传递给登录页面
      })
    } else {
      // 如果有token，正常导航到目标路由

      next()
    }
  } else {
    // 如果不需要认证，正常导航到目标路由
    next()
  }
})

export default router
